//
// Created by yubin on 2021/4/5.
//

#include "dlinklist.h"
#include <iostream>


namespace dl {

    void InitDLinkList(DLinkList &L)
    {
        L = new DNode;
        L->data = 0;
        L->prior = nullptr;
        L->next = nullptr;
    }

    void DestroyDLinkList(DLinkList &L)
    {
        DNode* curr = L;
        while (curr != nullptr) {
            auto next = curr->next;
            delete curr;
            curr = next;
        }
    }

    DNode* GetItem(DLinkList& L, int i) {
        if (i < 0)  // 不合法
            return nullptr;
        if (i == 0)  // 表示返回头结点
            return L;

        auto iter = L->next;
        int j = 1;
        while (iter != nullptr) {
            if (j == i)
                return iter;
            j++;
            iter = iter->next;
        }
        return nullptr;
    }

    DLinkList ListTailInsert(DLinkList &L)
    {
        int x;
        DNode* s;
        DNode* rear = L;

        std::cin >> x;
        while (x != 9999) {
            s = new DNode;
            s->data = x;
            s->next = nullptr;
            s->prior = rear;
            rear->next = s;
            rear = s;

            std::cin >> x;
        }
        return L;
    }

    bool InsertNode(DLinkList &L, ElemType e, int i)
    {
        if (i < 0)
            return false;

        auto s = new DNode;
        s->data = e;

        auto p = GetItem(L, i - 1);
        s->prior = p;
        s->next = p->next;
        p->next->prior = s;
        p->next = s;

        return true;
    }

    bool DeleteNode(DLinkList &L, int i)
    {
        if (i < 0)
            return false;

        auto p = GetItem(L ,i - 1);
        if (p == nullptr)
            return false;

        auto s = p->next;
        if (s == nullptr)
            return false;

        p->next = s->next;
        s->next->prior = s;
        delete s;

        return true;
    }

    bool PrintDLinkList(DLinkList &L)
    {
        auto pFirstNode = L->next;
        if (pFirstNode == nullptr) {
            std::cout << "Null LinkList";
        }
        std::cout << pFirstNode->data;
        auto p = pFirstNode->next;
        while (p != nullptr) {
            std::cout << " -> " << p->data;
            p = p->next;
        }
    }
}